<template>
  <div class="nav-wrapper">
    <el-menu
      class="nav-header"
      mode="horizontal"
      :ellipsis="false"
      router
    >
      <div class="logo-container">
        <el-menu-item index="/" class="logo-menu-item">
          <Logo />
        </el-menu-item>
      </div>

      <div class="flex-grow" />
      
      <el-menu-item index="/">
        <el-icon><House/></el-icon>首页
      </el-menu-item>
      <el-menu-item index="/services">
        <el-icon><List /></el-icon>服务分类
      </el-menu-item>
      <el-menu-item index="/staff">
        <el-icon><User /></el-icon>服务人员
      </el-menu-item>
      <el-menu-item index="/about">
        <el-icon><InfoFilled /></el-icon>关于我们
      </el-menu-item>

      <div class="auth-section">
        <template v-if="isLoggedIn">
          <el-dropdown trigger="click">
            <div class="user-profile-link">
              <div class="avatar-container">
                <el-avatar 
                  :size="32" 
                  :src="avatarUrl" 
                  class="user-avatar"
                >
                  <el-icon><UserFilled /></el-icon>
                </el-avatar>
              </div>
              <span class="username">{{ userStore.userInfo?.nickname || '个人中心' }}</span>
              <el-icon class="el-icon--right"><CaretBottom /></el-icon>
            </div>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item @click="$router.push('/profile')">
                  <el-icon><User /></el-icon>
                  <span>个人信息</span>
                </el-dropdown-item>
                <el-dropdown-item @click="$router.push('/my-orders')">
                  <el-icon><Document /></el-icon>
                  <span>我的订单</span>
                </el-dropdown-item>
                <el-dropdown-item @click="$router.push('/browse-history')">
                  <el-icon><Clock /></el-icon>
                  <span>浏览历史</span>
                </el-dropdown-item>
                <el-dropdown-item @click="showFavorites">
                  <el-icon><Star /></el-icon>
                  <span>我的收藏</span>
                </el-dropdown-item>
                <el-dropdown-item @click="showChat">
                  <div class="menu-item-content">
                    <div class="left">
                      <el-icon><Message /></el-icon>
                      <span>我的消息</span>
                    </div>
                  </div>
                </el-dropdown-item>
                <el-dropdown-item divided @click="handleLogout">
                  <el-icon><SwitchButton /></el-icon>
                  <span>退出登录</span>
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </template>
        <template v-else>
          <el-button 
            link 
            class="login-btn"
            @click="$router.push('/login')"
          >
            登录
          </el-button>
          <el-button 
            type="primary" 
            class="register-btn"
            @click="$router.push('/register')"
          >
            注册
          </el-button>
        </template>
      </div>
    </el-menu>
  </div>

  <my-favorites-dialog
    v-model="favoritesDialogVisible"
    @close="favoritesDialogVisible = false"
  />

  <chat-window v-model="chatVisible" />
</template>

<script setup>
import { computed, ref, onMounted, onUnmounted } from 'vue'
import { useUserStore } from '@/store/user'
import { useRouter } from 'vue-router'
import fileUtils from '@/utils/fileUtils'
import {
  User,
  UserFilled,
  CaretBottom,
  List,
  InfoFilled,
  Document,
  SwitchButton,
  Star,
  Clock,
  Message, House
} from '@element-plus/icons-vue'
import Logo from '@/components/common/Logo.vue'
import MyFavoritesDialog from './MyFavoritesDialog.vue'
import ChatWindow from '@/components/common/ChatWindow.vue'
import { ElMessageBox, ElMessage } from 'element-plus'

const userStore = useUserStore()
const router = useRouter()
const ws = ref(null)

const isLoggedIn = computed(() => !!userStore.token)

// 计算头像URL
const avatarUrl = computed(() => {
  const avatar = userStore.userInfo?.avatar
  return avatar ? fileUtils.getImageUrl(avatar) : ''
})

// 连接 WebSocket
const connectWebSocket = () => {
  if (ws.value?.readyState === WebSocket.OPEN) {
    console.log('WebSocket已经连接')
    return
  }

  // 使用相对路径，避免硬编码主机名和端口
  const wsProtocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:'
  const wsUrl = `${wsProtocol}//${window.location.hostname}:1234/websocket/chat/${userStore.userInfo?.id}`

  try {
    ws.value = new WebSocket(wsUrl)
    
    ws.value.onopen = () => {
      console.log('WebSocket连接已建立')
    }
    
    ws.value.onmessage = (event) => {
      try {
        const message = JSON.parse(event.data)
        console.log('收到WebSocket消息:', message)
        // 触发自定义事件，通知聊天窗口更新消息
        if (message.type === 'message') {
          document.dispatchEvent(new CustomEvent('new-message', { detail: message }))
        }
      } catch (error) {
        console.error('解析消息失败:', error)
      }
    }
    
    ws.value.onclose = (event) => {
      console.log('WebSocket连接已关闭', event.code, event.reason)
      // 如果不是正常关闭，尝试重连
      if (event.code !== 1000) {
        setTimeout(() => {
          console.log('尝试重新连接WebSocket')
          connectWebSocket()
        }, 3000)
      }
    }
    
    ws.value.onerror = (error) => {
      console.error('WebSocket连接错误:', error)
    }
  } catch (error) {
    console.error('创建WebSocket连接失败:', error)
  }
}

const handleLogout = async () => {
  try {
    await ElMessageBox.confirm('确认要退出登录吗?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    await userStore.logout()
    ElMessage.success('退出登录成功')
    router.push('/')
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('退出登录失败')
      console.error('Logout error:', error)
    }
  }
}

const favoritesDialogVisible = ref(false)
const chatVisible = ref(false)

onMounted(() => {
  if (isLoggedIn.value) {
    connectWebSocket()
  }
})

onUnmounted(() => {
  if (ws.value) {
    ws.value.close()
  }
})

const showFavorites = () => {
  favoritesDialogVisible.value = true
}

const showChat = () => {
  chatVisible.value = true
}
</script>

<style scoped>
.nav-wrapper {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 1000;
  background-color: #fff;
}

.nav-header {
  height: 64px;
  box-shadow: 0 1px 4px rgba(0,0,0,0.05);
  padding: 0 24px;
  max-width: 1400px;
  margin: 0 auto;
}

.logo-container {
  display: flex;
  align-items: center;
}

.logo-menu-item {
  padding: 0 20px !important;
}

.flex-grow {
  flex-grow: 1;
}

.auth-section {
  display: flex;
  align-items: center;
  gap: 16px;
  margin-left: 24px;
  height: 100%;
}

.user-profile-link {
  display: flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;
  padding: 2px 8px;
  border-radius: 6px;
  transition: all 0.3s;
}

.user-profile-link:hover {
  background: var(--el-color-primary-light-9);
}

.username {
  font-size: 14px;
  color: var(--el-text-color-primary);
}

.user-avatar {
  background: var(--el-color-primary-light-8);
  color: var(--el-color-primary);
}

/* 添加头像图片样式 */
.user-avatar :deep(img) {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

:deep(.menu-item-content) {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
  min-height: 40px;
  line-height: 40px;
}

:deep(.menu-item-content .left) {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 15px;
  height: 40px;
  line-height: 40px;
}

:deep(.menu-item-content .left span) {
  display: flex;
  align-items: center;
  height: 40px;
  line-height: 40px;
}

.login-btn {
  font-size: 14px;
}

.register-btn {
  padding: 8px 20px;
  border-radius: 6px;
}

.avatar-container {
  position: relative;
  display: inline-block;
}
</style> 